package com.shop.myweb.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.myweb.common.R;
import com.shop.myweb.entity.DTO.OrderDTO;
import com.shop.myweb.entity.Goods;
import com.shop.myweb.entity.Orders;
import com.shop.myweb.service.GoodsService;
import com.shop.myweb.service.OrdersService;
import com.shop.myweb.service.UserService;
import com.shop.myweb.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {


    @Autowired
    private OrdersService ordersService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/{id}")
    public R<Orders> queryOrdersById(@PathVariable Long id) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, id);
        Orders orders = ordersService.getOne(queryWrapper);
        return R.success(orders);
    }

    @GetMapping("/user/{id}")
    public R<List<Orders>> queryOrdersByUserId(@PathVariable Long id) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, id);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        List<Orders> list = ordersService.list(queryWrapper);
        return R.success(list);
    }


    @PutMapping("/edit")
    public R<String> update(@RequestBody OrderDTO orderDTO) {
        log.info("修改订单信息");
        Orders orders = orderDTO.getOrders();
        int page = orderDTO.getPage();
        int pageSize = orderDTO.getPageSize();
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "orderPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        ordersService.updateById(orders);
        return R.success("修改成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {

        //构造分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);


        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "orderPage_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) != null) {
                pageInfo = (Page<Orders>) redisTemplate.opsForValue().get(key);
                return R.success(pageInfo);
            }
            //构造条件构造器
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.orderByDesc(Orders::getOrderTime);
            ordersService.page(pageInfo, queryWrapper);
            redisTemplate.opsForValue().set(key, pageInfo, 60, TimeUnit.SECONDS);
        } else {
            //条件构造器
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(Orders::getOrderTime);
            //执行分页查询
            ordersService.page(pageInfo, queryWrapper);
        }
        return R.success(pageInfo);


    }

    /**
     * 购买商品
     *
     * @param orders
     * @return
     */
    @PostMapping
    @Transactional
    public R<String> saveOne(@RequestBody Orders orders) {
        //修改库存
        Long goodsId = orders.getGoodsId();
        Goods goods = goodsService.getById(goodsId);
        if (goods.getAmount() < orders.getAmount()) {
            return R.error("[" + goods.getName() + "]库存不足，请选择小于" + goods.getAmount() + "件");
        }
        goods.setAmount(goods.getAmount() - orders.getAmount());
        goodsService.updateById(goods);
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goods_" + goodsId;
            goods = (Goods) redisTemplate.opsForValue().get(key);
            if (goods != null) {
                redisTemplate.delete(key);
            }
        }
        //购买
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        ordersService.save(orders);
        return R.success("购买成功！");
    }

    @PostMapping("/list")
    @Transactional
    public R<String> saveList(@RequestBody List<Orders> ordersList) {
        boolean b = true;
        for (Orders orders : ordersList) {
            //修改库存
            Long goodsId = orders.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            if (goods.getAmount() < orders.getAmount()) {
                return R.error("[" + goods.getName() + "]库存不足，请选择小于" + goods.getAmount() + "件");
            }
            goods.setAmount(goods.getAmount() - orders.getAmount());
            goodsService.updateById(goods);
            //购买
            orders.setGoodsName(goods.getName());
            orders.setGoodsDetail(goods.getDescription());
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);
            ordersService.save(orders);
            if (RedisUtils.isRedisAvailable(redisTemplate)) {
                String key = "goods_" + goodsId;
                goods = (Goods) redisTemplate.opsForValue().get(key);
                if (goods != null) {
                    redisTemplate.delete(key);
                }
            }
        }
        return R.success("购买成功！");
    }


    @DeleteMapping
    public R<String> delete(Long id, Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page(page, pageSize);

        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "orderPage_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) != null) {
                redisTemplate.delete(key);
            }
        }
        ordersService.removeById(id);
        return R.success("取消成功！");
    }

}
